__author__ = 'Soul'
from core.Configurator import *
from core.Singleton import *
import json

class DbOperatorFactory(Singleton):
    def __init__(self):
         db_config_file = Configurator.get_val('db_conf')
         fp = open(db_config_file)
         self.__db_config_list__ = json.load(fp)
         self.__find_defults()
         fp.close()

    def __find_defults(self):
        self.__default_db_key__ = ""
        if len(self.__db_config_list__):
            for db_cfg in self.__db_config_list__:
                if db_cfg['db_default']:
                    self.__default_db_key__ = db_cfg['db_key']

            if self.__default_db_key__ == "":
                self.__default_db_key__ = self.__db_config_list__[0]['db_key']


    def GetDbOperator(self, dbname):
        if dbname == "":
            dbname = self.__default_db_key__

        from connection.MysqlDbConnection import MysqlDbConnection
        from connection.SqliteDbConnection import SqliteDbConnection

        '''
        Question: Do we need to maintain a connect pool here?
        '''

        for db_cfg in self.__db_config_list__:
            if db_cfg['db_key'] == dbname:
                conn = None
                clss_name = db_cfg['db_class']
                if db_cfg['db_type'] == "mysql":
                    conn = MysqlDbConnection(db_cfg['db_host'],
                                             db_cfg['db_port'],
                                             db_cfg['db_user'],
                                             db_cfg['db_pasw'],
                                             db_cfg['db_name'])
                elif db_cfg['db_type'] == "sqlite":
                    conn = SqliteDbConnection(db_cfg['db_file'])
                elif db_cfg['db_type'] == "sqlserver":
                    pass
                elif db_cfg['db_type'] == "oracle":
                    pass

                if conn == None or clss_name == None: return None

                module = __import__("dboperater.operators." + clss_name)
                module = getattr(module, clss_name)
                newclass = getattr(module, clss_name)
                operator = newclass(conn)

                return operator
        return None

